package com.polaris.live.ui.message.fragment.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.FragmentDialogMessageSingleBinding
import com.polaris.live.im.sfs.SYSTEM_USER_ID
import com.polaris.live.translation.R.string
import com.polaris.live.ui.message.fragment.MessageSingleFragment
import com.polaris.live.utils.fragment.attachFragment
import com.polaris.live.viewmodel.message.MessageViewModel
import com.vanniktech.emoji.EmojiPopup

/**
 * 直播的私聊列表
 *
 * @author Created by lucas on 2023/10/28 10:52
 */
class MessageSingleDialogFragment(
    private val otherId: Long = -1L,
    private val avatar: String? = null,
    private val avatarFrame: String? = null,
    private val chatBubble: String? = null,
    private val nestedPage: Boolean = false,
    private val singlePage: Boolean = false,
    private val needClickAvatar: Boolean = true,
) : KeyboardBottomDialogFragment() {

    override fun setStyle() {
        setStyle(
            STYLE_NO_FRAME,
            if (singlePage) R.style.DialogFragmentBottomDialog_Keyboard_Single else R.style.DialogFragmentBottomDialog_Keyboard
        )
    }

    override fun getAnimationStyle(): Int {
        return if (singlePage) {
            super.getAnimationStyle()
        } else {
            R.style.RightDialogAnimation
        }
    }

    override fun getDialogHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    private val mViewModel by viewModels<MessageViewModel>()

    private lateinit var mBinding: FragmentDialogMessageSingleBinding
    private lateinit var emojiPopup: EmojiPopup

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        return FragmentDialogMessageSingleBinding.inflate(inflater, container, false).let {
            mBinding = it

            it.root
        }
    }

    override fun onShowKeyboard() {
        mFragment.scrollToBottom()
    }

    override fun onHideKeyboard() {
        mBinding.etText.clearFocus()
    }

    private val mFragment by lazy {
        childFragmentManager.attachFragment(R.id.fl_fragment) {
            MessageSingleFragment().apply {
                arguments = bundleOf(
                    "otherId" to otherId,
                    "nestedPage" to nestedPage,
                    "avatar" to avatar,
                    "avatarFrame" to avatarFrame,
                    "chatBubble" to chatBubble,
                    LiveConst.Params.NEED_CLICK_AVATAR to needClickAvatar,
                )
            }
        }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()

        //系统消息没有回复，所以底部需要特殊处理
        if (otherId == SYSTEM_USER_ID) {
            mBinding.flRoot.fitsSystemWindows = false
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        mFragment.setOnSetStateNormal {
            KeyboardUtils.hideSoftInput(mBinding.etText)
        }

        //如果是重建回来的，不做数据初始化
        if (otherId != -1L) {
            initData()
        }
    }

    private fun initView() {
        emojiPopup = EmojiPopup(
            mBinding.root,
            mBinding.etText,
            popupWindowHeight = KeyboardUtil.getKeyboardHeight(context)
        )

        //强制设置大小一致
        mBinding.clContent.layoutParams = mBinding.clContent.layoutParams.also {
            if (it is FrameLayout.LayoutParams) {
                it.topMargin = getTopMargin() + if (otherId == SYSTEM_USER_ID) {
                    0
                } else {
                    -BarUtils.getStatusBarHeight()
                }
            }
        }

        if (otherId == SYSTEM_USER_ID) {
            mBinding.vBottomLine.visibility = View.GONE
            mBinding.llEdit.visibility = View.GONE
        }
        mBinding.flRoot.setOnClickListener {
            dismiss()
        }
        mBinding.bvTitle.setOnLeftClientListener {
            dismiss()
        }
        mViewModel.infoOtherLiveData.observe(this) { resultState ->
            parseState(resultState, { user ->
                mBinding.bvTitle.setTitle(user.nickname)
                mFragment.setAvatar(
                    user.avatar,
                    user.decoration?.avatarFrame,
                    user.decoration?.chatBubble
                )
                mFragment.setInfoOtherResp(user)
            })

        }
        mBinding.ivEmoji.setOnClickListener {
            emojiPopup.toggle()
        }
        mBinding.ivSend.setOnClickListener {
            if (otherId == -1L) {
                return@setOnClickListener
            }

            val text = mBinding.etText.text?.toString()
            if (text.isNullOrBlank()) {
                ToastGravity.showGravity(getString(string.content_noncompliance))
            } else {
                mBinding.etText.text = null
                text.let { it1 ->
                    mViewModel.sendTextMessage(
                        requireContext(),
                        otherId,
                        it1,
                        mFragment.getPushDetailId()
                    )
                }
                KeyboardUtils.hideSoftInput(mBinding.etText)
            }
        }
    }

    private fun initData() {
        if (otherId == SYSTEM_USER_ID) {
            mBinding.bvTitle.setTitle(
                StringUtils.getString(string.app_name) + " " + StringUtils.getString(
                    string.team
                )
            )
        } else {
            mViewModel.getInfoUser(
                otherId,
                false,
                UserManager.BASIC_INFORMATION,
                UserManager.DECORATIVE_DISPLAY
            )
        }
    }
}